﻿using CoachingOrganizer.ClientInfrastructure.ServicesEntities.LocalStorage;
using CoachingOrganizer.Logic.Common;
using CoachingOrganizer.Logic.Models.Common;
using CoachingOrganizer.Toolkit.Events;
using CoachingOrganizer.Toolkit.Patterns;
using CoachingOrganizer.Toolkit.Threading.CollectionsDecorators;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CoachingOrganizer.Logic.Logic.Common
{
    internal class InteractionLogic : DisposableObject
    {
        private readonly InteractionModel _model;
        private readonly LogicExtender _logicExtender;
        private readonly List<PeriodLogic> _periods = new List<PeriodLogic>();

        public InteractionLogic(InteractionModel model, LogicExtender logicExtender)
        {
            _model = model;
            _logicExtender = logicExtender;
            _model.EnumeratePeriodsDelegate = EnumeratePeriods;
            _model.AddNewPeriodDelegate = AddNewPeriod;
        }

        public ActionResult RemovePeriod(PeriodLogic logicObject)
        {
            ActionResult outResult = logicObject.LocalData.Remove();
            if (outResult.IsValid)
            {
                _periods.Remove(logicObject);
                _model.ModifyPeriodsCollection(col => col.Remove(logicObject.Model));
            }
            return outResult;
        }

        private ActionResult<IEnumerable<PeriodLogic>> EnumeratePeriods()
        {
            ActionResult<IEnumerable<IPeriodInfo>> periodsInfoResult = _logicExtender.ServicesFactory.GetCurrentLocalStorageService().EnumeratePeriods();
            return periodsInfoResult.IsValid ? ActionResult<IEnumerable<PeriodLogic>>.GetValidResult(periodsInfoResult.Result.Select(i => CreatePeriodLogic(i))) : ActionResult<IEnumerable<PeriodLogic>>.GetErrorResult(periodsInfoResult);
        }

        private ActionResult<PeriodLogic> AddNewPeriod()
        {
            ActionResult<IPeriodInfo> addResult = _logicExtender.ServicesFactory.GetCurrentLocalStorageService().CreateNewPeriod();
            return addResult.IsValid ? ActionResult<PeriodLogic>.GetValidResult(CreatePeriodLogic(addResult.Result)) : ActionResult<PeriodLogic>.GetErrorResult(addResult);
        }

        private PeriodLogic CreatePeriodLogic(IPeriodInfo info)
        {
            PeriodLogic outResult = new PeriodLogic(new PeriodModel
            {
                StartDate = info.Start,
                FinishDate = info.Finish
            }, _logicExtender, this, info);
            _periods.Add(outResult);
            return outResult;
        }
    }
}
